package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
	"strconv"
	"time"
)

type GoodsController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 添加

func (c *GoodsController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	cate := c.GetString("cate")
	img := c.GetString("img")
	info := c.GetString("info")
	goods := models.Goods{
		Name:  name,
		Price: price,
		Cate:  cate,
		Img:   img,
		Info:  info,
	}
	err := models.DB.Create(&goods).Error
	if err != nil {
		res := JsonRes{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}

}

// 列表

func (c *GoodsController) List() {
	page, _ := c.GetInt("page", 1) //当前页
	size, _ := c.GetInt("size", 5) //每页条数
	query := models.DB.Debug().Model(&models.Goods{})
	name := c.GetString("name") //接收搜索的关键词
	//接收搜索关键字，判断关键字是否为空，不为空就拼接where条件
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	key := "page-" + strconv.Itoa(page) + "-" + name //page-1-华为
	val, err := models.RedisDb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		var count int64
		query.Count(&count)
		offset := (page - 1) * size //偏移量
		var goods []models.Goods
		err = query.Order("price asc").Offset(offset).Limit(size).Find(&goods).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {

			pageData["count"] = count
			pageData["goods"] = goods
			jsonByte, _ := json.Marshal(&pageData)
			value := string(jsonByte)
			models.RedisDb.Set(key, value, time.Minute*10)

			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}

}

// 删除(软删除)

func (c *GoodsController) Delete() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("id = ?", id).Delete(&models.Goods{}).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		key := "goods-" + strconv.Itoa(id)
		models.RedisDb.Del(key)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}

// 修改

func (c *GoodsController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	cate := c.GetString("cate")
	img := c.GetString("img")
	info := c.GetString("info")
	goods := models.Goods{
		Name:  name,
		Price: price,
		Cate:  cate,
		Img:   img,
		Info:  info,
	}
	err := models.DB.Where("id = ?", id).Updates(&goods).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 缓存：使用redis 提升网站访问速度，减少对mysql的请求次数，减轻对数据库造成的压力
// 商品详情

func (c *GoodsController) Info() {
	//key 键 ----》 value 值
	id, _ := c.GetInt("id")            /// 999
	key := "goods-" + strconv.Itoa(id) // goods-999
	var goods models.Goods
	val, err := models.RedisDb.Get(key).Result()
	// 缓存使用思路： 判断缓存中是否有数据，有的话就直接读取缓存，没有的话先查询数据库，并存入redis缓存
	if err != nil {
		// 查询 mysql数据库
		err = models.DB.Where("id = ?", id).First(&goods).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
		}
		// 存入缓存
		jsonByte, _ := json.Marshal(&goods)
		value := string(jsonByte)
		models.RedisDb.Set(key, value, time.Minute*10)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-Mysql",
			Data: goods,
		}
		c.ServeJSON()
	} else {
		// 数据反转
		json.Unmarshal([]byte(val), &goods)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-Redis",
			Data: goods,
		}
		c.ServeJSON()

	}
}
